package com.yixq.soa.service.user;

import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter4;
import com.yixq.soa.service.web.argresolver.DoorduMethodParameterResolver;
import com.yixq.soa.service.web.auth.DoorduAuthInterceptor;
import com.yixq.soa.service.web.auth.interceptor.TokenInterceptor;
import com.yixq.soa.service.web.cache.GlobalCacheManager;
import com.yixq.soa.service.web.converter.String2DateConverter;
import com.yixq.soa.service.web.converter.String2LocalDateConverter;
import com.yixq.soa.service.web.converter.String2LocalDateTimeConverter;
import com.yixq.soa.service.web.utils.DoorduRequestMappingHandlerMapping;
import com.google.common.collect.Lists;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.ImportAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.format.FormatterRegistry;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import java.nio.charset.Charset;
import java.util.List;


/**
 * 用于加载额外的定义配置.
 * 
 * @author kyler.tang
 *
 */
@SpringBootApplication
@ComponentScan(basePackages={"com.yixq.soa.service.user,com.yixq.soa.service.web.auth"})
@Configuration
@ImportResource(value = { "classpath:application-beans.xml" })
@EnableCaching 
@ImportAutoConfiguration({com.yixq.soa.service.web.CommWebConifg.class})
public class ConfigClass extends WebMvcConfigurationSupport {
	static Logger log = LoggerFactory.getLogger(ConfigClass.class);
    @Value("${executor.coresize}")
    private Integer coresize;
    @Value("${executor.maxsize}")
    private Integer maxsize;
    @Value("${executor.queuesize}")
    private Integer queuesize;
    @Value("${executor.keepalived}")
    private Integer keepAlived;

	@Autowired
	private RedisTemplate jedisTemplate;

	@Autowired
	private JedisConnectionFactory jedisConnectionFactory;

	public ConfigClass() {
		// JSON.DEFFAULT_DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";// json 日期格式

	}


	@Override
	protected void addFormatters(FormatterRegistry registry) {
        registry.addConverter(new String2DateConverter());// 添加 String - Date 的参数转换器
        registry.addConverter(new String2LocalDateConverter());
		registry.addConverter(new String2LocalDateTimeConverter());
		super.addFormatters(registry);
	}

	@Override
	protected void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
		StringHttpMessageConverter smc = new StringHttpMessageConverter(Charset.forName("UTF-8"));
		converters.add(smc);
		FastJsonHttpMessageConverter4 fjmc = new FastJsonHttpMessageConverter4();
		fjmc.setSupportedMediaTypes(
				Lists.newArrayList(MediaType.APPLICATION_JSON_UTF8, MediaType.TEXT_PLAIN, MediaType.ALL));

		fjmc.setDefaultCharset(Charset.forName("utf-8"));

		FastJsonConfig config = new FastJsonConfig();
		// config.setDateFormat("yyyy-MM-dd HH:mm:ss");
		config.setSerializerFeatures(SerializerFeature.WriteDateUseDateFormat, SerializerFeature.WriteNullStringAsEmpty,
				SerializerFeature.WriteMapNullValue);// 默认时间转换格式
		fjmc.setFastJsonConfig(config);

		converters.add(fjmc);

		super.configureMessageConverters(converters);
	}

	@Override
	public void addResourceHandlers(ResourceHandlerRegistry registry) {
		registry.addResourceHandler("/**").addResourceLocations("classpath:/webapp/");
		super.addResourceHandlers(registry);

    }

	@Override
	@Bean
	public RequestMappingHandlerMapping requestMappingHandlerMapping() {
		RequestMappingHandlerMapping handlerMapping = new DoorduRequestMappingHandlerMapping();
		handlerMapping.setOrder(0);
		handlerMapping.setInterceptors(getInterceptors());
		return handlerMapping;
	}

	@Override
	protected void addInterceptors(InterceptorRegistry registry) {
		registry.addInterceptor(new DoorduAuthInterceptor()).addPathPatterns("/**");
		//registry.addInterceptor(new TokenInterceptor()).addPathPatterns("/**");

        //DoorduSessionStrategy.TOKEN_KEY = "_session";

        super.addInterceptors(registry);
	}

	@Override
	protected void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
		argumentResolvers.add(new DoorduMethodParameterResolver());
	}

	@Bean
	public CacheManager cacheManager() {
		RedisTemplate redisTemplate = new RedisTemplate();
		redisTemplate.setConnectionFactory(jedisConnectionFactory);
		redisTemplate.afterPropertiesSet();
		return new GlobalCacheManager(jedisTemplate);
	}
}
